//
//  ZSOAuthController.swift
//  新浪微博-Swift
//
//  Created by 周李波 on 16/7/20.
//  Copyright © 2016年 q. All rights reserved.
//

import UIKit
import SVProgressHUD

class ZSOAuthController: UIViewController {
    //MARK:- 加载视图
    override func loadView() {
        //拼接url
        let urlString = "https://api.weibo.com/oauth2/authorize?client_id=\(APPKEY)&redirect_uri=\(APPREDIRECT_URI)"
        
        let u = NSURL(string: urlString)
        guard let url = u else{
            return
        }
        let request = NSURLRequest(URL: url)
        //加载webview
        webView.loadRequest(request)
        webView.delegate = self
        //显示
        view = webView
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        setupUI()
    }
    //MARK:- 设置UI
    func setupUI(){
        view.backgroundColor = UIColor.whiteColor()
        
        navigationItem.title = "微博登陆"
        navigationItem.leftBarButtonItem = ZSBarButtonItem(title: "取消", imageName: nil, target: self, action: #selector(ZSOAuthController.cancelClick))
        navigationItem.rightBarButtonItem = ZSBarButtonItem(title: "自动填充", imageName: nil, target: self, action: #selector(ZSOAuthController.fillButtonClick))
        //导航栏下面插入视图
        navigationController?.view.insertSubview(progressView, belowSubview: navigationController!.navigationBar)
    }
    //MARK:- 取消按钮
    @objc private func cancelClick(){
        dismissViewControllerAnimated(true, completion: nil)
    }
    //MARK:- 填充按钮点击
    @objc private func fillButtonClick(){
        //JS注入
        let jsString = "document.getElementById('userId').value='\(WEIBONAME)',document.getElementById('passwd').value='\(WEIBOPASSWORD)'"
        webView.stringByEvaluatingJavaScriptFromString(jsString)
        
    }
    
    //MARK:- 懒加载控件
    lazy var webView:UIWebView = UIWebView()
    lazy var progressView:ZSProgressView = ZSProgressView()
    
}
//MARK:- 代理方法
extension ZSOAuthController:UIWebViewDelegate{
    //开始加载
    func webViewDidStartLoad(webView: UIWebView) {
        progressView.startAnim()
        SVProgressHUD.show()
        
    }
    //结束加载
    func webViewDidFinishLoad(webView: UIWebView) {
        progressView.endAnim()
        SVProgressHUD.dismiss()
    }
    //加载错误
    func webView(webView: UIWebView, didFailLoadWithError error: NSError?) {
        
    }
    //正在加载
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        //请求的字符串
//        print(request)
        let urlString = request.URL?.absoluteString
       
        if let u = urlString where u.hasPrefix(APPREDIRECT_URI) {
            let query = request.URL?.query
            
            if let q = query {
                let code = q.substringFromIndex("code=".endIndex)
                print(code)
            }
        }
        
        
        
        return true
    }

    
}

